package com.imooc.zhousc.controller;

import com.imooc.zhousc.util.ZookeeperLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class ZookeeperLockController {

    @GetMapping("zkLock")
    public String zkLock(){
        log.info("我进入了方法");
        try(ZookeeperLock zookeeperLock = new ZookeeperLock()){
            if (zookeeperLock.getLock("order")){
                log.info("我获得了锁");
                Thread.sleep(15000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("方法执行完成");
        return "ok";
    }

    @Autowired
    private CuratorFramework client;

    @GetMapping("curatorLock")
    public String curatorLock(){
        log.info("我进入了方法");
        InterProcessMutex lock = new InterProcessMutex(client, "/order");
        try {
            if ( lock.acquire(30, TimeUnit.SECONDS) ) {
                log.info("我获得了锁");
                Thread.sleep(10000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.info("方法执行完成");
        return "ok";
    }
}
